﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using TriggerInfo = SimpleBoard.Trigger.Trigger;

namespace SimpleBoard.Backend.Server.Services
{
    public class TriggerService
    {
        public TriggerService()
        {
            triggers = new();
            PendingTriggers = new();
            ExecutingTriggers = new();
        }

        public List<(TriggerInfo, int)> PendingTriggers { get; private set; }
        public BlockingCollection<TriggerInfo> ExecutingTriggers { get; private set; }

        private readonly Dictionary<string, TriggerInfo> triggers;

        public bool AddTrigger(TriggerInfo trigger)
        {
            if (triggers.ContainsKey(trigger.Name)) return false;
            return true;
        }

        public void ExcuteTrigger(string type, Guid target, object value)
        {
            var fitTriggers = triggers.Values.Where(x => x.TargetType == type)
                                      .Where(x => x.TargetId == target)
                                      .Where(x => x.IsEnabled);
            foreach (var trigger in fitTriggers)
            {
                if (trigger.IsFitConditions(value))
                {
                    ExecutingTriggers.Add(trigger);
                    PendingTriggers.Add(new(trigger, trigger.Interval));
                }
            }
        }
    }
}
